package com.string.actortv.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Process;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import androidx.core.app.ActivityCompat;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.string.actortv.R;
import com.string.actortv.activity.fanfei.FanFeiTypeActivity;
import com.string.actortv.activity.jxtcd.JxtcdTypeActivity;
import com.string.actortv.activity.qmmk.QmmkTypeActivity;
import com.string.actortv.config.Config;
import com.string.actortv.dto.UpdateInfoModel;
import com.string.actortv.receiver.UpdateReceiver;
import com.string.actortv.util.CacheHelper;
import com.string.actortv.util.MyHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends Activity {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static boolean main_initialized = false;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private Context mContext = null;
    private SimpleAdapter gridAdapter;
    private GridView gridView;
    private View selectedView;
    private ArrayList<HashMap<String, Object>> items;
    private UpdateReceiver mUpdateReceiver;
    private IntentFilter mIntentFilter;

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_season_list);
        mContext = this;

        if (!main_initialized) {
            this.newInit();
            registerBroadcast();
            MyHttpUtil.getAsync(Config.UPDATE_URL, result -> {
//                Log.d("wuyiunlei", result);
                JSONObject object = JSONObject.parseObject(result);
                UpdateInfoModel model = new UpdateInfoModel();
                model.setAppname(object.getString("appname"));
                model.setServerFlag(object.getString("serverFlag"));
                model.setServerVersion(object.getString("serverVersion"));
                model.setUpdateurl(object.getString("updateurl"));
                model.setUpgradeinfo(object.getString("upgradeinfo"));
                CacheHelper.CACHE.put(CacheHelper.KEY_APP_UPDATE, model);
                verifyStoragePermissions(this);
                //发送广播
                sendBroadcast(new Intent(UpdateReceiver.UPDATE_ACTION));
            }, null);
        } else {
            try {
                unRegisterBroadcast();
            } catch (Exception ignore) {

            }
        }

    }

    /**
     * 广播注册
     */
    private void registerBroadcast() {
        mUpdateReceiver = new UpdateReceiver(false);
        mIntentFilter = new IntentFilter(UpdateReceiver.UPDATE_ACTION);
        this.registerReceiver(mUpdateReceiver, mIntentFilter);
    }

    /**
     * 广播卸载
     */
    private void unRegisterBroadcast() {
        try {
            this.unregisterReceiver(mUpdateReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        this.newInit();
        super.onResume();
    }

    private void newInit() {
        items = new ArrayList<>();
        this.gridView = this.findViewById(R.id.item_grid);
        if (gridView == null) {
            throw new IllegalArgumentException("the gridView is null");
        }

        items = new ArrayList<>();
        //奇妙萌可
        HashMap<String, Object> item = new HashMap<>();
        item.put("title", "奇妙萌可");
        item.put("icon", "https://www.jxtcd.com/favicon.ico");
        items.add(item);

        //策驰影院电影
        item = new HashMap<>();
        item.put("title", "策驰影院电影");
        item.put("icon", "https://www.jxtcd.com/favicon.ico");
        items.add(item);

        //策驰影院动漫
        item = new HashMap<>();
        item.put("title", "策驰影院动漫");
        item.put("icon", "https://www.jxtcd.com/favicon.ico");
        items.add(item);

        //梵菲电影网电视剧
        item = new HashMap<>();
        item.put("title", "梵菲电影网电视剧");
        item.put("icon", "https://www.fanfeifan.com/template/mytheme/statics/image/20240212/2571ba92c.ico");
        items.add(item);

        //梵菲电影网电影
        item = new HashMap<>();
        item.put("title", "梵菲电影网电影");
        item.put("icon", "https://www.fanfeifan.com/template/mytheme/statics/image/20240212/2571ba92c.ico");
        items.add(item);

        //收藏夹
        item = new HashMap<>();
        item.put("title", "收藏夹");
        item.put("icon", R.drawable.play_favorite);
        items.add(item);

        //本地历史记录
        item = new HashMap<>();
        item.put("title", "本地历史记录");
        item.put("icon", R.drawable.play_history);
        items.add(item);

        this.gridAdapter = new SimpleAdapter(this, items,
                R.layout.function_block, new String[]{"title", "icon"},
                new int[]{R.id.Item_text, R.id.Item_bt});

        gridAdapter.setViewBinder((view, data, textRepresentation) -> {
            //判断是否为我们要处理的对象
            if (view instanceof ImageView && data instanceof String) {
                ImageView iv = (ImageView) view;
                Glide.with(this).load(data.toString()).error(R.drawable.no_pic).into(iv);
                return true;
            } else {
                return false;
            }
        });

        if (null != this.gridView) {
            this.gridView.setAdapter(gridAdapter);
            this.gridAdapter.notifyDataSetChanged();

            this.gridView.setOnItemClickListener((gridView, view, position, id) -> {
                Intent intent1;
                switch (position) {
                    case 0:
                        //策驰影院电视剧
                        intent1 = new Intent(MainActivity.this,
                                QmmkTypeActivity.class);
                        MainActivity.this.startActivity(intent1);
                        break;
                    case 1:
                        //策驰影院电影
                        intent1 = new Intent(MainActivity.this,
                                JxtcdTypeActivity.class).setAction("1");
                        MainActivity.this.startActivity(intent1);
                        break;
                    case 2:
                        //策驰影院动漫
                        intent1 = new Intent(MainActivity.this,
                                JxtcdTypeActivity.class).setAction("3");
                        MainActivity.this.startActivity(intent1);
                        break;
                    case 3:
                        //梵菲电影网电视剧
                        intent1 = new Intent(MainActivity.this,
                                FanFeiTypeActivity.class).setAction("2");
                        MainActivity.this.startActivity(intent1);
                        break;
                    case 4:
                        //梵菲电影网电影
                        intent1 = new Intent(MainActivity.this,
                                FanFeiTypeActivity.class).setAction("1");
                        MainActivity.this.startActivity(intent1);
                        break;
                    case 5:
                        //收藏夹
                        intent1 = new Intent(MainActivity.this,
                                FavoriteActivity.class);
                        MainActivity.this.startActivity(intent1);
                        break;
                    case 6:
                        //历史记录
                        intent1 = new Intent(MainActivity.this,
                                HistoryActivity.class);
                        MainActivity.this.startActivity(intent1);
                        break;
                    default:

                }
            });

            this.gridView.setOnFocusChangeListener((v, hasFocus) -> {
                if (hasFocus) {
                    if (selectedView != null) {
                        selectedView.setBackgroundColor(Color.WHITE);
                    }
                    View first = gridView.getChildAt(0);
                    if (first != null) {
                        first.setBackgroundColor(Color.GRAY);
                        selectedView = first;
                    }
                } else {
                    if (selectedView != null) {
                        selectedView.setBackgroundColor(Color.WHITE);
                        selectedView = null;
                    }
                }
            });

            this.gridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (selectedView != null) {
                        selectedView.setBackgroundColor(Color.WHITE);
                    }
                    if (view != null) {
                        view.setBackgroundColor(Color.GRAY);
                        selectedView = view;
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    if (selectedView != null) {
                        selectedView.setBackgroundColor(Color.WHITE);
                        selectedView = null;
                    }
                }

            });

        }
        main_initialized = true;

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                this.tbsSuiteExit();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void tbsSuiteExit() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setTitle("好剧快查");
        dialog.setPositiveButton("是", (dialog1, which) -> {
            Process.killProcess(Process.myPid());
        });
        dialog.setMessage("现在退出?");
        dialog.create().show();
    }

}
